package com.cn.redis.client.impl;

import com.cn.redis.client.RedisClient;
import com.cn.redis.exception.RedisConnectException;
import com.cn.redis.properties.RedisProperties;
import com.cn.redis.utils.b;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

public class a implements RedisClient {
    private RedisProperties redisProperties;
    private volatile b E;
    private static final int F = 3;

    public a(RedisProperties redisProperties) {
        this.redisProperties = redisProperties;
    }

    public void init() {
        JedisCluster pools = this.G();
        this.a(pools);
    }

    public long incrBy(String seqName, int step) {
        long max = 0L;

        for(int i = 0; i < 3; ++i) {
            try {
                try {
                    JedisCluster pool = this.F();

                    try {
                        max = pool.incrBy(seqName, Long.valueOf((long)step));
                        if (max > 0L) {
                            break;
                        }
                    } catch (Exception var13) {
                        var13.printStackTrace();
                    } finally {
                        if (pool != null) {
                            pool.close();
                        }

                    }
                } catch (Exception var15) {
                    var15.printStackTrace();
                    throw new RedisConnectException("redis连接失败");
                }
            } catch (Exception var16) {
                var16.printStackTrace();
                throw new RedisConnectException("redis连接失败");
            }
        }

        return max;
    }

    private void a(JedisCluster tempPool) {
        this.E = (new b.a(tempPool)).I();
    }

    private JedisCluster F() {
        return this.E.G();
    }

    public JedisCluster G() {
        Set<HostAndPort> nodes = new HashSet();
        String[] ipPort = this.redisProperties.getClusterNodes().split(",");

        for(int i = 0; i < ipPort.length; ++i) {
            String[] ipAndPort = ipPort[i].split(":");
            nodes.add(new HostAndPort(ipAndPort[0], Integer.valueOf(ipAndPort[1])));
        }

        JedisCluster cluster = new JedisCluster(nodes, this.getPoolConfig());
        return cluster;
    }

    public GenericObjectPoolConfig getPoolConfig() {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setTestOnBorrow(false);
        config.setTestOnReturn(false);
        config.setTestWhileIdle(true);
        config.setMinIdle(8);
        config.setMaxWaitMillis(10L);
        return config;
    }
}
